package com.patrick.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.ArrayList;
import java.util.List;

//解码器
public class Decoder extends ByteToMessageDecoder {

    ByteBuf msg = Unpooled.buffer();

    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {


//        合并
        ByteBuf message = null;
        int size = msg.readableBytes();
        if (size > 0) {
            message = Unpooled.buffer();
            message.writeBytes(msg);
            message.writeBytes(byteBuf);
        } else {
            message = byteBuf;
        }
//        解析
        int s = message.readableBytes();
        int counter = s / 17;
        for (int i = 0; i < counter; i++) {
            GpsInfo gpsInfo = new GpsInfo();
            byte[] carNo = new byte[8];
            message.readBytes(carNo);
            gpsInfo.setCarNo(new String(carNo));
            byte[] lon = new byte[5];
            message.readBytes(lon);
            gpsInfo.setCarNo(new String(lon));
            byte[] lat = new byte[4];
            message.readBytes(lat);
            gpsInfo.setCarNo(new String(lat));

            out.add(gpsInfo);
        }
//        缓冲
//        剩余
        int ss = message.readableBytes();
        if(ss>0){
            System.out.println("多余的数据");
            msg.clear();
            msg.writeBytes(message);
        }
    }
}
